package com.sumer.psychology.blog.domain.model;

import com.sumer.psychology.blog.application.command.CreateBlogCommand;
import com.sumer.psychology.common.Assert;
import org.apache.commons.lang3.StringUtils;

/**
 * Blog制造工厂
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/9/4
 * Time: 18:05
 */
public class BlogFactory {
    private static BlogFactory blogFactory = new BlogFactory();

    public static BlogFactory instance() {
        return blogFactory;
    }

    private BlogFactory() {
    }

    /**
     * 制造一个Blog，根据博客内容、目录、标签等
     *
     * @param aCreateBlogCommand command
     * @param blogRepository     blog
     * @param categoryRepository category
     * @return blog
     */
    public Blog createBlog(CreateBlogCommand aCreateBlogCommand,
                           BlogRepository blogRepository,
                           CategoryRepository categoryRepository) {
        Blog aBlog = new Blog(blogRepository.nextIdentity(),
                aCreateBlogCommand.author(),
                aCreateBlogCommand.title(),
                aCreateBlogCommand.content());

        Category aCategory = createCategory(
                aCreateBlogCommand,
                categoryRepository);

        if (aCategory != null) {
            aBlog.categorizeInto(aCategory);
        }

        return aBlog;
    }

    /*
     * 产生一个目录
     */
    private Category createCategory(CreateBlogCommand aCreateBlogCommand,
                                    CategoryRepository categoryRepository) {
        if (StringUtils.isNotBlank(aCreateBlogCommand.categoryId())) {// 是否有分类
            Category aCategory = categoryRepository.activeCategoryOfId(
                    new CategoryId(aCreateBlogCommand.categoryId()));

            Assert.notNull(aCategory, "目录不能为空");
            return aCategory;
        }
        return null;
    }

}
